
package de.unihannover.se.restlab.microblog.data;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

import de.unihannover.se.restlab.microblog.models.Message;
import de.unihannover.se.restlab.microblog.models.User;

/** A list of messages.
 * @author restlab_c */
@Stateless
@XmlRootElement
@XmlType(namespace = "http://www.w3.org/2005/AtomMessageStorage")
public class MessageStorage extends AbstractStorage  {
	
	public static MessageStorage getStorage() {
    	return (MessageStorage) getConcreteStorage(MessageStorage.class);
	}
	
	@PersistenceContext
	private EntityManager em;

	@XmlElement(name = "message")
	private List<Message> messages = new ArrayList<Message>();

	public Message createMessage (User user, String content, Integer parentId) {
		Integer nextId = 1;
		if (!messages.isEmpty()) {
			nextId = messages.size() + 1;
		}
		Message message = new Message(nextId, user, content, parentId != null ? parentId : -1);
		messages.add(message);
		
		//em.persist(new de.unihannover.se.restlab.microblog.jpamodels.Message(message));
		em.persist(message.getPersistence());
		
		//em.getTransaction().commit();
		//em.close();
		
		return message;
	}

	public List<Message> getMessages () {
		return messages;
	}

	public Message getMessage (Integer id) {
		return (id < messages.size()) ? messages.get(id - 1) : null;
	}

	public void clear () {
		setup();
		for(Message m : messages) {
			em.remove(m.getPersistence());
		}
		messages.clear();
	}

	public void setup () {
		int i=1;
		while(true) {
			de.unihannover.se.restlab.microblog.jpamodels.Message m = em.find(de.unihannover.se.restlab.microblog.jpamodels.Message.class, i++);
			if(m == null) break;
			messages.add(new Message(m));
		}
	}

}
